import { useUserStore } from "@/store/userStore";
import { useSceneStore, type SceneType } from "@/store/sceneStore";
import { useFurnitureStore } from "@/store/furnitureStore";
import type { IItem } from "@/type/item";
import { getCellPosition, loadImage } from ".";
import { checkCollision, isRectanglesOverlap } from "./collision";
import { globalScale } from "@/config/static";

interface PlacedFurniture {
  id: string; // 家具实例ID
  furnitureId: string; // 家具类型ID
  position: {
    // 家具放置位置
    x: number;
    y: number;
  };
  rotation: number; // 家具旋转角度
  sceneType: SceneType; // 场景类型
  itemData: IItem;
}

export class FurniturePlacer {
  private isPlacingMode: boolean = false; // 是否处于放置家具模式
  private selectedFurnitureId: string | null = null; // 当前选中的家具ID
  private selectedFurniture: any = null; // 当前选中的家具
  private rotation: number = 0; // 当前选中的家具的旋转角度
  private userStore = useUserStore();
  private sceneStore = useSceneStore();
  private furnitureStore = useFurnitureStore();
  private placedFurniture: PlacedFurniture[] = []; // 放置的家具列表
  private furnitureImages: Record<string, HTMLImageElement> = {}; // 家具图片缓存

  constructor() {
    this.loadPlacedFurniture();
    this.preloadFurnitureImages();
  }

  /**
   * 加载已放置的家具
   */
  loadPlacedFurniture() {
    this.furnitureStore.initFurniture();
    this.placedFurniture = this.furnitureStore.placedFurniture;
  }

  /**
   * 预加载家具的图片
   */
  private preloadFurnitureImages() {
    // 获取所有家具的类型ID
    const uniqueFurnitureIds = new Set(
      this.placedFurniture.map((f) => f.furnitureId)
    );

    uniqueFurnitureIds.forEach(async (furnitureId) => {
      const furniture = this.placedFurniture.find(
        (f) => f.furnitureId === furnitureId
      );

      if (furniture && furniture.itemData && furniture.itemData.imageUrl) {
        try {
          this.furnitureImages[furnitureId] = await loadImage(
            furniture.itemData.imageUrl
          );
        } catch (error) {
          console.error(`加载家具图片失败：${furnitureId}`, error);
        }
      }
    });
  }

  /**
   * 检查是否可以放置家具
   * @param x 放置位置的x坐标
   * @param y 放置位置的y坐标
   * @param item 要放置的物品
   * @returns 是否可以放置
   */
  public canPlaceFurniture(x: number, y: number, item: IItem): boolean {
    if (!item || !item.placeable) {
      return false;
    }

    const drawWidth = item.sourceRect.drawWidth;
    const drawHeight = item.sourceRect.drawHeight;

    if (
      checkCollision(
        Math.floor(x),
        Math.floor(y),
        drawWidth,
        drawHeight,
        "item"
      )
    ) {
      console.log("与地图发生碰撞");
      return false;
    }

    console.log("没有发生碰撞");

    return true;
  }

  /**
   * 放置家具
   * @param x 放置位置的x坐标
   * @param y 放置位置的y坐标
   * @param item 要放置的家具
   * @returns 是否成功放置家具
   */
  public placeFurniture(x: number, y: number, item: IItem): boolean {
    if (!this.canPlaceFurniture(x, y, item)) {
      console.log(`放置家具失败 ${item.name} 在位置 ${x},${y}`);
      return false;
    }
    this.furnitureStore.addFurniture(
      item.id,
      { x, y },
      this.rotation,
      this.sceneStore.currentScene,
      item
    );

    console.log(`放置家具成功 ${item.name} 在位置 ${x},${y}`);

    this.loadPlacedFurniture();

    return true;
  }
}

export const furniturePlacer = new FurniturePlacer();
